package jeecg.hh.mvc.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class AnnotationClassloader extends ClassLoader {

	public AnnotationClassloader(){}
	
	 public AnnotationClassloader(ClassLoader parent){
		 super(parent);
	 }
	
	private String rootDir;
	
	public AnnotationClassloader(String rootDir){
		this.rootDir=rootDir;
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		// TODO Auto-generated method stub
		byte[] classData=getClassData(name);
		if(classData==null){
			throw new ClassNotFoundException();
		}else{
			Class<?> clazz= defineClass(name, classData, 0, classData.length);
			AnnotationParse.initResourceAnnotation(clazz.getName());
			return clazz;
		}
	}
	
	private byte[] getClassData(String className){
		String path=classNameToPath(className);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		try {
			InputStream ins = new FileInputStream(path);
			int bufferSize=4096;
			byte[] buffer=new byte[bufferSize];
			int bytesNumRead=0;
			while((bytesNumRead=ins.read(buffer))!=-1){
				baos.write(buffer,0,bytesNumRead);
			}
			return baos.toByteArray();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private String classNameToPath(String className){
		return "D:/Apple.class";
//		return rootDir+File.separatorChar+className.replace('.', File.separatorChar)+".class";
	}
	
}
